import os
import pandas as pd
#loading dataset
import pandas as pd
import numpy as np
#visualisation
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
#EDA
from collections import Counter
# data preprocessing
from sklearn.preprocessing import StandardScaler
# data splitting
from sklearn.model_selection import train_test_split
# data modeling
from sklearn.metrics import confusion_matrix,accuracy_score,roc_curve,classification_report
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
# 数据文件
current_dir = os.path.dirname(__file__)
src_data_path = os.path.join(current_dir, '../pre_process/heart.csv')


def train():
    # 加载数据
    data = pd.read_csv(src_data_path, encoding='utf-8')
    y = data["target"]
    X = data.drop('target',axis=1)
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state = 0)
    # LR分类器
    lr = LogisticRegression()
    model = lr.fit(X_train, y_train)
    lr_predict = lr.predict(X_test)
    lr_conf_matrix = confusion_matrix(y_test, lr_predict)
    lr_acc_score = accuracy_score(y_test, lr_predict)
    print("confussion matrix")
    print(lr_conf_matrix)
    print("\n")
    print("Accuracy of Logistic Regression:",lr_acc_score*100,'\n')
    print(classification_report(y_test,lr_predict))
    # KNN分类器
    knn = KNeighborsClassifier(n_neighbors=10)
    knn.fit(X_train, y_train)
    knn_predicted = knn.predict(X_test)
    knn_conf_matrix = confusion_matrix(y_test, knn_predicted)
    knn_acc_score = accuracy_score(y_test, knn_predicted)
    print("confussion matrix")
    print(knn_conf_matrix)
    print("\n")
    print("Accuracy of K-NeighborsClassifier:",knn_acc_score*100,'\n')
    print(classification_report(y_test,knn_predicted))
    # SVM分类器
    svc =  SVC(kernel='rbf', C=2)
    svc.fit(X_train, y_train)
    svc_predicted = svc.predict(X_test)
    svc_conf_matrix = confusion_matrix(y_test, svc_predicted)
    svc_acc_score = accuracy_score(y_test, svc_predicted)
    print("confussion matrix")
    print(svc_conf_matrix)
    print("\n")
    print("Accuracy of Support Vector Classifier:",svc_acc_score*100,'\n')
    print(classification_report(y_test,svc_predicted))

    # 计算TP和FP
    lr_false_positive_rate,lr_true_positive_rate,lr_threshold = roc_curve(y_test,lr_predict)
    knn_false_positive_rate,knn_true_positive_rate,knn_threshold = roc_curve(y_test,knn_predicted)
    svc_false_positive_rate,svc_true_positive_rate,svc_threshold = roc_curve(y_test,svc_predicted)

    # 绘制TFFP曲线对比图
    plt.figure(figsize=(10,5))
    plt.title('Reciver Operating Characterstic Curve')
    plt.plot(lr_false_positive_rate,lr_true_positive_rate,label='Logistic Regression')
    plt.plot(knn_false_positive_rate,knn_true_positive_rate,label='K-Nearest Neighbor')
    plt.plot(svc_false_positive_rate,svc_true_positive_rate,label='Support Vector Classifier')
    plt.plot([0,1],ls='--')
    plt.plot([0,0],[1,0],c='.5')
    plt.plot([1,1],c='.5')
    plt.ylabel('True positive rate')
    plt.xlabel('False positive rate')
    plt.legend()
    plt.savefig(os.path.join(current_dir,"TP-FP_Comparation.png"))
    # plt.show()

    # 绘制准确度对比图
    model_ev = pd.DataFrame({'Model': ['Logistic Regression','K-Nearest Neighbour','Support Vector Machine'], 'Accuracy': [
            lr_acc_score*100,knn_acc_score*100,svc_acc_score*100]})
    colors = ['red','green','blue','gold','silver','yellow','orange']
    plt.figure(figsize=(12,5))
    plt.title("barplot Represent Accuracy of different models")
    plt.xlabel("Accuracy %")
    plt.ylabel("Algorithms")
    plt.bar(model_ev['Model'],model_ev['Accuracy'],color = colors)
    plt.savefig(os.path.join(current_dir,"AccuracyComparation.png"))
    # plt.show()
    
    return ["TP-FP_Comparation.png", "AccuracyComparation.png"]